package com.hbun.cxcy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hbun.cxcy.common.utils.PageUtils;
import com.hbun.cxcy.entity.Apply;
import com.hbun.cxcy.entity.File;
import com.hbun.cxcy.mapper.ApplyMapper;
import com.hbun.cxcy.service.ApplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbun.cxcy.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hbun.cxcy.common.utils.Query;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mahaunyu
 * @since 2022-01-24
 */
@Service
public class ApplyServiceImpl extends ServiceImpl<ApplyMapper, Apply> implements ApplyService {

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Autowired
    FileService fileService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        IPage<Apply> page = this.page(
                new Query<Apply>().getPage(params),
                new QueryWrapper<Apply>().orderByDesc("update_time")
        );

        return new PageUtils(page);


    }

    // TODO 需要搞懂
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveWithCustom(Apply apply) {
        try {
            // 由于是网站post提交，不能让用户自主选择状态，所以需要后台手动添加
            apply.setStatus(1);
            Date date = new Date();
            apply.setCreateTime(dateFormat.format(date));
            apply.setUpdateTime(dateFormat.format(date));
            this.save(apply);
            // 添加到file表
            String url = apply.getUrl();
            if (!StringUtils.isEmpty(url)) {
                File file = new File();
                String suffix = url.split("\\.")[1];
                String[] strings = url.split("/");
                String name = strings[strings.length - 1];
                String type = "apply";
                file.setType(type);
                file.setName(name);
                file.setStatus(1);
                file.setSuffix(suffix);
                file.setFilePath(url);
                file.setCreateTime(new Date());
                file.setUpdateTime(new Date());
                fileService.save(file);
            }

        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }

    }

    @Override
    public void updateByIdWithTime(Apply apply) {
        Date date = new Date();
        apply.setUpdateTime(dateFormat.format(date));
        this.updateById(apply);
    }

    @Override
    public void removeByIdsWithCustom(List<Long> ids) {
        // 逻辑删除
        for (Long id : ids) {
            Apply apply = this.baseMapper.selectById(id);
            apply.setStatus(0);
            this.updateById(apply);
        }

    }

    //根据专业分组的柱状图
    @Override
    public Map<String, Object> selectGroupByProfessional() {
        Map<String, Object> res = new HashMap<>();
        QueryWrapper<Apply> wrapper = new QueryWrapper<Apply>().eq("status", 1);

        wrapper.select("professional,count(*) as nums").groupBy("professional");
        List<Map<String, Object>> maps = this.listMaps(wrapper);
        System.out.println(maps);
        List<String> data1 = new ArrayList<>();
        List<Integer> data2 = new ArrayList<>();
        maps.forEach(item -> {
            data1.add(item.get("professional").toString());
            data2.add(Integer.parseInt(item.get("nums").toString()));
        });
        res.put("data1", data1);
        res.put("data2", data2);
        return res;

    }

    //每日人数折线图
    @Override
    public Map<String, Object> everyDayPeople() {
        Map<String, Object> res = new HashMap<>();

        QueryWrapper<Apply> wrapper = new QueryWrapper<Apply>().eq("status", 1);

        wrapper.select("create_time as createTime,count(*) as nums").groupBy("create_time");
        List<String> data1 = new ArrayList<>();
        List<Integer> data2 = new ArrayList<>();
        List<Map<String, Object>> maps = this.listMaps(wrapper);
        maps.forEach(item -> {
            data1.add(item.get("createTime").toString());
            data2.add(Integer.parseInt(item.get("nums").toString()));
        });
        res.put("data1", data1);
        res.put("data2", data2);
        return res;
    }

    @Override
    public Map<String, Object> deptGroupBy() {
        Map<String, Object> res = new HashMap<>();
        QueryWrapper<Apply> wrapper = new QueryWrapper<Apply>().eq("status", 1);

        wrapper.select("dept_name as deptName,count(*) as nums").groupBy("dept_name");
        List<Map<String, Object>> maps = this.listMaps(wrapper);
        List<String> data1 = new ArrayList<>();
        List<Integer> data2 = new ArrayList<>();
        System.out.println(maps);
        maps.forEach(item -> {
            data1.add(item.get("deptName").toString());
            data2.add(Integer.parseInt(item.get("nums").toString()));
        });
        res.put("data1", data1);
        res.put("data2", data2);
        return res;
    }

    @Override
    public Map<String, Object> sexGroupBy() {
        Map<String, Object> res = new HashMap<>();
        QueryWrapper<Apply> wrapper = new QueryWrapper<Apply>().eq("status", 1);

        wrapper.select("sex ,count(*) as nums").groupBy("sex");
        List<Map<String, Object>> maps = this.listMaps(wrapper);
        List<String> data1 = new ArrayList<>();
        List<Integer> data2 = new ArrayList<>();
        maps.forEach(item -> {
            data1.add(item.get("sex").toString());
            data2.add(Integer.parseInt(item.get("nums").toString()));
        });
        res.put("data1", data1);
        res.put("data2", data2);
        return res;
    }

    //饼图
    @Override
    public Map<String, Object> selectGroupByProfessionalToPie() {
        Map<String, Object> res = new HashMap<>();
        QueryWrapper<Apply> wrapper = new QueryWrapper<Apply>().eq("status", 1);
        wrapper.select("professional,count(*) as nums").groupBy("professional");
        List<Map<String, Object>> maps = this.listMaps(wrapper);
        System.out.println(maps);
        List<String> data1 = new ArrayList<>();
        List<Map<String, Object>> data2 = new ArrayList<>();
        maps.forEach(item -> {
            data1.add(item.get("professional").toString());
            Map<String, Object> map = new HashMap<>();
            map.put("name", item.get("professional"));
            map.put("value", item.get("nums"));
            data2.add(map);
        });
        res.put("data1", data1);
        res.put("data2", data2);
        return res;

    }
}
